package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println(password + "password");
        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     *
     * @param employeeDTO
     */
    public void add(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 对象属性拷贝,将employeeDTO中的属性拷贝到employee中,前提是两个对象中的属性名相同，第一个参数是源，第二个参数是目标
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置实体类的其他属性的值
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        // employee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());
        // 设置创建人和修改人的id
        // Long currentId = BaseContext.getCurrentId();
        // employee.setCreateUser(currentId);
        // employee.setUpdateUser(currentId);
        employeeMapper.insert(employee);
    }

    public PageResult queryPage(EmployeePageQueryDTO employeePageQueryDTO) {
        // PageHelper底层使用的是拦截器，拦截器会拦截到我们的sql语句，然后在sql语句后面拼接limit语句，并且使用count查询总记录数
        // 将传进去的页码每页数量存到ThreadLocal中，然后再sql中取出来拼到limit后
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        // 返回page是使用PageHelper后必须返回这个类型
        Page<Employee> page = employeeMapper.queryPage(employeePageQueryDTO);
        // 将查询结果封装到PageResult中进行返回，
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    /**
     * 根据id设置账号状态
     *
     * @param id
     * @return
     */
    public void setStatus(Integer status, long id) {
        // 这里可以传递一个实体类进去，实体类的值设置为传递过来的值，这样SQL语句就只用写一句，如果下次有个更新员工姓名什么的实现类，也可以使用同一个SQL语句
        // Employ实体类上有builder注解，所以可以使用builder模式进行赋值，不用一个个set
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        employeeMapper.update(employee);
    }

    @Override
    public Employee getUserInfo(Long id) {
        Employee employee = employeeMapper.getUserById(id);
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

}
